#include <QgsSimulation/ProcessTool.h>
namespace SimulationCore
{
	namespace QgsSimulation
	{
		int get_base_layer(QVector<QgsRasterLayer*> layers, const QString & name)
		{
			if (layers.size() > 0) {
				for (int i = 0; i < layers.size(); ++i) {
					QgsRasterLayer* raster_layer = layers[i];
					if (raster_layer->name() == name) {
						return i;
					}
				}
			}
			return -1;
		}

		QgsRectangle get_round_rect(const QgsRectangle & rect)
		{
			double left = std::ceil(rect.xMinimum());
			double top = std::floor(rect.yMaximum());
			double right = std::floor(rect.xMaximum());
			double bottom = std::ceil(rect.yMinimum());

			return QgsRectangle(left, bottom, right, top);
		}

		QgsVectorLayer* get_base_layer(QVector<QgsVectorLayer*> layers, const QString & name)
		{
			if (layers.size() > 0) {
				for (int i = 0; i < layers.size(); ++i) {
					QgsVectorLayer* v_layer = layers[i];
					if (v_layer && v_layer->name() == name) {
						return v_layer;
					}
				}
			}
			return nullptr;
		}

		QgsVectorLayer * get_framework_layer(QVector<QgsVectorLayer*> layers, const QString & name, QgsWkbTypes::Type type)
		{
			if (layers.size() > 0) {
				for (int i = 0; i < layers.size(); ++i) {
					QgsVectorLayer* v_layer = layers[i];
					if (v_layer->name() == name &&v_layer->wkbType() == type) {
						return v_layer;
					}
				}
			}
			return nullptr;
		}

		QgsFeatureId get_maxarea_featureid(QgsVectorLayer * v_layer)
		{
			QgsFeatureId id;
			double area = 0;
			QgsFeatureIterator it = v_layer->getFeatures();
			QgsFeature feature;
			while (it.nextFeature(feature)) {
				auto geometry = feature.geometry();
				auto geo_area = geometry.area();
				if (geo_area > area) {
					area = geo_area;
					id = feature.id();
				}
			}
			if (!it.isClosed()) {
				it.close();
			}
			return id;
		}


		void create_mkdir(const QString & filename)
		{
			//use qfileinfo get file path
			QFileInfo file_info(filename);
			QString directory_path = file_info.path();

			QDir dir(directory_path);
			if (!dir.exists()) {
				dir.mkpath(directory_path);
			}
		}

		void create_dir(const QString & path)
		{
			QDir dir(path);
			if (!dir.exists()) {
				dir.mkpath(path);
			}
		}

		void delete_dir(const QString & path)
		{
			QDir dir(path);
			if (dir.exists()) {
				dir.removeRecursively();
			}
		}

		QString get_driver_letter(const QString & path)
		{
			int index = path.indexOf(":");
			if (index == 1 && path[0].isLetter()) {
				return path.left(2);
			}
			return QString();
		}

        double CalculateAngle(const QgsPointXY & p1, const QgsPointXY & p2)
		{
			auto dx = p2.x() - p1.x();
			auto dy = p2.y() - p1.y();
			return (atan2(dy, dx) * 180 / M_PI);
		}

        void RotationApply(const QgsPointXY & p1, double angle, QgsGeometry & geom)
		{
			angle = angle * M_PI / 180;
			QTransform transform;
			transform.translate(p1.x(), p1.y());
			transform.rotateRadians(angle);
			transform.translate(-p1.x(), -p1.y());
			geom.transform(transform);
		}


	}
}
